package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author xiexiaoyu
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    private StringUtils ObjectUtil;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //校验老人是否已经入住
        //获取老人身份证号码
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        String idCardNo = checkInElderDto.getIdCardNo();
        //根据号码校验老人是否在入住
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Elder::getIdCardNo,idCardNo).in(Elder::getStatus,1,4);
        Elder elder = elderMapper.selectOne(lambdaQueryWrapper);
        if(ObjectUtils.isNotEmpty(elder)){
            throw new RuntimeException("该老人已经入住");
        }
        //更新床位状态为已入住
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //新增或更新老人
            //更新老人的基本信息和床位信息
        Elder elder2 = updateOrInsertBaseAndBedInfo(checkInElderDto, bed);

        //新增签约办理
        insertContract(elder2, checkInApplyDto);

        //新增入住信息（家属信息）
        CheckIn checkIn = insertCheckInInfo(elder2, checkInApplyDto.getCheckInConfigDto(), bed, checkInApplyDto.getElderFamilyDtoList());

        //新增入住配置
        insertCheckInConfig(checkIn, checkInApplyDto.getCheckInConfigDto());

    }

    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckInInfo(Elder elder2, CheckInConfigDto checkInConfigDto, Bed bed, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder2.getName());
        checkIn.setElderId(elder2.getId());
        checkIn.setIdCardNo(elder2.getIdCardNo());
        BeanUtils.copyProperties(checkInConfigDto,checkIn);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(Elder elder2, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        Long id = elder2.getId();
        contract.setElderId(Integer.valueOf(String.valueOf(id)));

        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        BeanUtils.copyProperties(checkInContractDto,contract);

        String contractNumber = CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);

        contract.setElderName(elder2.getName());

        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStartDate(checkInConfigDto.getStartDate());
        //将合同状态改为未生效0
        contract.setStatus(0);

        contractMapper.insert(contract);
    }

    private Elder updateOrInsertBaseAndBedInfo(CheckInElderDto checkInElderDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        Elder elder1 = elderMapper.selectOne(wrapper);
        if(ObjectUtils.isNotEmpty(elder1)){
            //修改老人信息
            elderMapper.updateById(elder);
        }else {
            //新增老人信息
            elderMapper.insert(elder);
        }
        return elder;
    }

    @Override
    public CheckInDetailVo getDetail(Long id) {
        //id是checkInId
        CheckIn checkIn = checkInMapper.selectById(id);
        Long elderId = checkIn.getElderId();
        //查询入住信息
        Bed bed = bedMapper.selectBedById(id);
        //查询老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder,checkInElderVo);
        //问题：那不到老人的年龄？？？？？？？？？？？？？
        String idCardNo = elder.getIdCardNo();
        int age = IdcardUtil.getAgeByIdCard(idCardNo);
        checkInElderVo.setAge(age);
        //查询合同
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper();
        contractWrapper.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(contractWrapper);
        //查询入住配置
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        //转换家属列表
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
        //整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
